<template>
  <el-button
    type="primary"
    v-for="item in wujieSubAppsConfig"
    :key="item.name"
    @click="toggleSubApp(item)"
    >{{ item.name }}</el-button
  >
  <div class="wujie-micro"></div>
</template>
<script setup lang="ts">
import { wujieSubAppsConfig } from '@/config/wujie.config'
import { onMounted } from 'vue'
import { startApp, setupApp, type cacheOptions, type startOptions } from 'wujie'
onMounted(() => {
  wujieSubAppsConfig.forEach((app) => {
    setupApp(app)
  })
})
/**
 * 生命周期配置
 */
const lifeCycleConfig = (name: string | number) => {
  return {
    beforeLoad: () => {
      console.log('beforeLoad---应用' + name + '加载前的回调')
    },
    beforeMount: () => {
      console.log('beforeMount---应用' + name + '挂载前的回调')
    },
    afterMount: () => {
      console.log('afterMount---应用' + name + '挂载后的回调')
    },
    beforeUnmount: () => {
      console.log('beforeUnmount---应用' + name + '卸载前的回调')
    },
    afterUnmount: () => {
      console.log('afterUnmount---应用' + name + '卸载后的回调')
    },
    activated: () => {
      console.log('activated---应用' + name + '激活时的回调')
    },
    deactivated: () => {
      console.log('deactivated---应用' + name + '失活时的回调')
    },
    loadError: () => {
      console.log('loadError---应用' + name + '加载错误时的回调')
    }
  }
}
function toggleSubApp(item: cacheOptions) {
  const el = document.querySelector('.wujie-micro') as HTMLElement | null
  if (!el) return
  const { name, url = '', ...rest } = item
  const params: startOptions = {
    el,
    name,
    url,
    ...rest,
    ...lifeCycleConfig(name),
    plugins: [
      {
        // 在子应用所有的css之前
        // cssBeforeLoaders: [
        //   //在加载html所有的样式之前添加一个外联样式
        //   { src: '//unpkg.com/element-plus/dist/index.css' }
        //   //在加载html所有的样式之前添加一个内联样式
        // ],
        patchElementHook(element, iframeWindow) {
          if (element.nodeName === 'STYLE') {
            ;(element as any).insertAdjacentElement = function (_position: any, ele: any) {
              iframeWindow.document.head.appendChild(ele)
            }
          }
        }
      }
    ]
  }
  startApp(params)
}
</script>
<style scoped>
.wujie-micro {
  width: 100%;
  height: 100%;
}
</style>
